package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApCollectionService;
import com.heima.feigns.behavior.BehaviorFegin;
import com.heima.model.Utils.threadlocal.AppThreadLocalUtils;
import com.heima.model.article.dto.CollectionBehaviorDto;
import com.heima.model.article.pojo.ApCollection;
import com.heima.model.behavior.pojo.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojo.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by ZYJ on 2021/6/5 1:03
 */
@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {
    @Autowired
    BehaviorFegin behaviorFegin;

    /**
     * 用户收藏或取消收藏
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {

        if(dto == null ||dto.getEntryId() == null ||(dto.getType() !=0 &&dto.getType()!=1)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if(user == null || user.getId() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"请先登录");
        }
        //远程调用查询行为实体信息
        ApBehaviorEntry behaviorEntry = behaviorFegin.findBehaviorEntry(user.getId(), null);

        if(behaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApCollection apCollection = this.getOne(Wrappers.<ApCollection>lambdaQuery()
                .eq(ApCollection::getArticleId, dto.getEntryId())
                .eq(ApCollection::getEntryId, behaviorEntry.getId())
        );

        if(apCollection == null && dto.getOperation() == 0){
            apCollection = new ApCollection();
            apCollection.setEntryId(behaviorEntry.getId());
            apCollection.setArticleId(dto.getEntryId());
            apCollection.setType(dto.getType());
            apCollection.setCollectionTime(new Date());
            apCollection.setPublishedTime(dto.getPublishedTime());
            this.save(apCollection);
        }else {
            this.remove(Wrappers.<ApCollection>lambdaQuery()
                    .eq(ApCollection::getArticleId,dto.getEntryId())
                    .eq(ApCollection::getEntryId,behaviorEntry.getId())
            );
        }

        return ResponseResult.okResult();
    }
}
